<template>
  <view class="page" :class="isShowLoading ? 'page-load' : ''" :style="{background:model == 'inline'?'#f8f8f8':'#f8f8f8'}">
    <!-- 头部 start -->
	<fu-custom bgColor="bg-white" :isBack="true">
		<block slot="content">商城</block>
	</fu-custom>
	<view style="background-color: #fff;position: sticky;z-index: 99;" :style="[{ top: CustomBar + 'px' }]">
		<view class="cu-custom bg-white" style="height: 64rpx;">
		  <view class="cu-bar " style="height: 64rpx; padding: 0;">
		    <view class="search-form round">
		      <text class="cuIcon-search"></text>
		      <input
		        confirm-type="search"
		        type="text"
		        v-model="keywords"
		        :adjust-position="false"
		        :hold-keyboard="false"
		        :placeholder="placeholder"
		        @confirm="searchConfirm"
		        class="text-999"
		        placeholder-style="color:#999"
		      />
		      <text v-if="keywords.length != 0" class="cuIcon-close text-gray padding-right-xs" @tap="handleClear"></text>
		    </view>
		  </view>
		</view>
		<!-- 筛选 -->
		<fu-filter-dropdown :top="CustomBar+64" @changeLayout="changeLayout" @changeFilter="changeFilter" :filterKeyword="keywords" ref="childMethod" :cid="cid"></fu-filter-dropdown>
	</view>
    <!-- loading组件 -->
    <fu-loading v-if="isShowLoading"></fu-loading>
    <!-- 商品列表 -->
    <view v-else class="list">
		<block v-for="item in lists" :key="item.id" v-if="!isSearchShop">
			<fu-goods-block-four :info="item" @kanjia="kanjia(item)"></fu-goods-block-four>
		</block>
      <block v-for="item in lists" :key="item.id" v-if="isSearchShop">
        <view class="bg-white">
          <view class="solid-bottom fu-shop-item">
            <view class="fu-shop-logo"><fu-image :src="item.store_logo" mode="aspectFill" /></view>
            <view class="fu-shop-main">
              <view class="fu-shop-name">
                <text class="text-df text-black store_name text-bold">{{ item.store_name }}</text>
				<view class="text-sm fu-shop-go" @click.stop="goMerchant(item)">{{i18n['进店']}}</view>
              </view>
			  <view class="time flex align-center">
				  <view class="flex align-center">
					  <image src="https://localelife.chunchuangkeji.cn/h5img/images/clock.png" class="icon"></image>
					  <text>{{item.business_hours}}</text>
				  </view>
				  <view class="flex align-center">
					  <image src="https://localelife.chunchuangkeji.cn/h5img/images/tel.png" class="icon"></image>
					  <text>{{item.service_phone}}</text>
				  </view>
			  </view>
              <view class="address flex align-center">
				  <image src="https://localelife.chunchuangkeji.cn/h5img/images/addr-4.png" class="icon"></image>
				  <text class="text-sm text-gray" style="flex-shrink: 0;">{{item.juli}}</text>
				  <text class="text-sm text-gray" style="margin: 0 8rpx;"> | </text>
                <text class="text-sm text-gray addr">{{ item.company_address }}</text>
              </view>
            </view>
          </view>
        </view>
      </block>
      <!-- 悬浮按钮 -->
      <fu-floor :type="type" :isShow="isShow" :pageNum="totalSize" :currentPage="currentPage" v-if="totalSize > 1"></fu-floor>
      <!-- 空布局 -->
      <fu-empty-ui v-if="lists.length == 0 && isInit" emptyImage="goods"></fu-empty-ui>
      <!-- 加载状态 -->
      <uni-load-more v-if="lists.length > 0" :status="status"></uni-load-more>
    </view>
    <!-- 断网检测组件 -->
    <fu-notwork></fu-notwork>
  </view>
</template>
<script>
// 基础筛选与高级筛选组件
import FuFilterDropdown from '../components/fu-filter-dropdown/fu-filter-dropdown.vue';
import fuFloor from '../components/fu-floor/fu-floor.vue';
import FuGoodsBlockFour from '@/components/fu-goods-block-four/index.vue';
// 楼层效果混入js
import floor from '@/common/mixin/floor.js';

export default {
  components: {
    FuFilterDropdown,
    fuFloor,
	FuGoodsBlockFour
  },
  mixins: [floor],
  data() {
    return {
      timer: null, // 定时器
      type: 1, // 悬浮按钮状态 1 页码 2 返回顶部
      isShow: false, //是否显示按钮
      totalSize: 0, // 悬浮按钮总页码
      currentPage: 1, // 当前页页码
      isShowLoading: true, // 是否显示loading
      keywords: '', // 搜索的文本
      placeholder: global.i18n['请输入商品关键字'], // 默认文本
      model: 'inline', // 布局样式
      lists: [], // 结果列表
      cid: '', // 分类id(点击分类跳转过来必传)
      isInit: false, // 是否请求过数据
      status: 'more', // 加载状态
      page: 1, // 页数
      size: 10, // 页条数
      sorts: '1', // 条件
      order: 'asc', // 排序 asc: 正序 desc: 倒序
      advancedSearch: null, // 高级搜索对象
      isSearchShop: false // {Boolean} 是否是搜多店铺
    };
  },
  computed: {
	  location() {
	  	return this.$store.getters.location;
	  }
  },

  onLoad(options) {
    console.log(options, '搜索参数');
    /***
     * @keyWords 关键词
     * @cid 分类id
     **/
    const { keyWords = '', cid = '' } = options;
    if (keyWords) {
      this.keywords = keyWords;
    }
    if (cid != '') {
      this.cid = cid;
    }
    console.log(this.cid,'分类id')
    this.handleSearch(); // 搜索方法
		// this.searchConfirm(this.cid)
    uni.$on('updataShopInfo', data => {
      this.page = 1;
      this.status = 'more';
      this.handleSearch();
    });
  },
  onUnload() {
    uni.$off('updataShopInfo');
  },
  onReachBottom() {
    this.handleSearch(); // 搜索方法
  },
  async onShareAppMessage(res) {
  	console.log(res, 'hsaressss')
  	let info = {
  		title: '',
  		path: '',
  		imageUrl: ''
  	};
  	if (res.from == 'button') {
  		let data = res.target.dataset.item;
  		console.log(data, 'daaaaaa')
  		await this.$api.post(global.apiUrls.post6406d647c5828, {
  			goods_id: data.id,
			lng: this.location.longitude,
			lat: this.location.latitude,
			
  		}).then(res => {
  			if (res.data.code == 1) {
  				info.title = data.name
  				info.path = `/pages/goods/goodsdetail/goods-detail/index?goods_id=${data.id}&type=share`
  				info.imageUrl = data.thumb
  			} else {
  				this.$message.info(res.data.msg)
  				return false;
  			}
  		})
  	} else {
  		info.path = `pages/tab/home/shopindex/index`
  	}
  	if (info.path) {
  		return info;
  	}
  },
  methods: { 
		
    // 去店铺
    goMerchant(item) {
      this.$urouter.navigateTo({
        url: '/pages/goods/shop/shop/index',
        params: {
          partner_id: item.u_id
        }
      });
    },
    switchGrid() {
      this.model = this.model == 'inline' ? 'block' : 'inline';
	  
	  this.$forceUpdate()
      console.log(this.model);
    },
	kanjia(item) {
		this.$api.post(global.apiUrls.post64031a6b88f68, {
			goods_id: item.id
		}).then(res => {
			this.$message.info(res.data.msg)
			if (res.data.code == 1) {
				this.page = 1
				this.status = 'more'
				this.handleSearch()
			}
		})
	},
    /**
     * @event
     * @description 去商品详情
     */
    navToDetail(item) {
      this.$urouter.navigateTo({
        url: '/pages/goods/goodsdetail/goods-detail/index',
        params: {
          sku_id: item.sku_id || 0,
          goods_id: item.id
        }
      });
    },
    /***
     * @func 扫描搜商品
     **/
    hanldeScode() {
      const that = this;
      uni.scanCode({
        scanType: ['barCode'],
        success: function(response) {
          console.log('条码类型：' + response.scanType);
          console.log('条码内容：' + response.result);
          that.$api
            .post(global.apiUrls.postSearchScanCode, {
              sn: response.result
            })
            .then(res => {
              if (res.data.code == 1 && res.data.data.list.length > 0) {
                that.$urouter.navigateTo({
                  url: '/pages/goods/goodsdetail/goods-detail/index',
                  params: {
                    goods_id: res.data.data.list[0].id,
                    sku_id: res.data.data.list[0].sku_id || 0
                  }
                });
              } else {
                this.$message.info({
                  content: this.i18n['暂无相关数据']
                });
              }
            })
            .catch(err => {
              this.$message.info({
                content: this.i18n['暂无相关数据']
              });
              console.log('err: ' + JSON.stringify(err));
            });
        }
      });
    },
    /**
     * @description 切换布局
     * @param {Object} e inline和block布局切换
     */
    changeLayout(e) {
      console.log(e)
      this.model = e;
    },
    /**
     * @description 切换搜索条件
     * @param {Object} type 条件
     * @param {Object} order  排序 asc: 正序 desc: 倒序
     * @param {Object} advancedSearch 高级搜索对象
     */
    changeFilter(type, order, advancedSearch, isSearchShop) {
      console.log('xxxxxxx', type, order, advancedSearch, isSearchShop);
      if (isSearchShop) {
        this.model = 'inline';
      }
      this.sorts = ++type;
      this.order = order;
      this.page = 1;
      this.status = 'more';
      this.scrollInfo = []; // 清空楼层数量
      // 判断高级搜索存在
      if (advancedSearch) {
        this.advancedSearch = advancedSearch;
        this.sorts = 1;
        this.order = 'asc';
      }
      // 判断是否是搜索店铺
      this.isSearchShop = isSearchShop;

      console.log(advancedSearch);
      this.handleSearch();
      this.$nextTick(() => {
        // 切换条件回到底部
        uni.pageScrollTo({
          scrollTop: 0,
          duration: 0
        });
      });
    },
    /**
     * @description 切换搜索条件
     * @param {Object} e input框事件源
     */
    searchConfirm(e) {
      // if (e && e.detail.value.trim() == '') return;
      this.cid = 0;
      this.page = 1;
      this.status = 'more';
      this.scrollInfo = []; // 清空楼层数量
      if (this.$refs.childMethod) {
        this.$refs.childMethod.resetPop();
        this.advancedSearch = {
          typeId: 0,
		  goods_type: 0
        };
      }
      this.handleSearch();
      uni.hideKeyboard();
    },
    /**
     * @func 搜索
     */
    handleSearch() {
      if (this.status != 'more') return;
      this.status = 'loading';
      let data = {
        type: 7,
        sort: this.sorts,
        order: this.order,
        page: this.page,
        list_rows: this.size,
		lat: this.location.latitude,
		lng: this.location.longitude
      };
      // 判断是否是搜索店铺
      if (this.isSearchShop) {
        data.business_parameters = 'stores';
      }
		console.log(this.advancedSearch, 111111111111111)
		console.log(this.isSearchShop, 2222222222)
      //判断是否有高级搜索
      if (this.advancedSearch && !this.isSearchShop) {
        data.cid = this.advancedSearch.typeId;
		data.goods_type = this.advancedSearch.goods_type
      }
      console.log(data);
      // 判断关键字或者placeholder内容
      if (this.placeholder.trim() || this.keywords.trim()) {
        data.keyword = this.keywords;
        this.addHistory(this.keywords.trim());
      }
      // if(this.keywords.trim() == ''){
      //   this.$message.info("请输入搜索关键字");
      //   this.lists=[];
      //   return
      // }
      // 判断cid是否存在
      console.log(this.cid,'分类id2')
      if (this.cid) {
        data.cid = this.cid;
      }
      console.log('search data', data);
      if (this.page == 1) {
        this.isShowLoading = true;
      }
      console.log('ooooooooooooooooooo',data)
      // 获取商品列表接口
      this.$api
        .post(global.apiUrls.getGoodsGetGoodsList, data)
        .then(res => {
          this.isShowLoading = false;
          console.log('搜索结果', res);
          if (res.data.code == 1) {
            let totalSize = res.data.data.total;
            this.totalSize = Math.ceil(totalSize / 10); // 悬浮按钮总页码
            this.currentPage = this.page; //悬浮当前页面
            console.log(res.data.data);
            let list = res.data.data.data;
            if (this.page == 1) this.lists = [];
            if (list) {
              if (this.isSearchShop) {
                list.forEach(item => {
                  this.lists.push(item.shop_info);
                });
              } else {
                this.lists = this.lists.concat(list);
              }
            }
            console.log(this.lists);
            if (this.lists.length >= totalSize) {
              this.status = 'noMore';
            } else {
              this.status = 'more';
              this.page++;
            }
            this.isInit = true;
          } else {
            this.$message.info(res.data.msg);
          }
        })
        .catch(err => {
          this.isShowLoading = false;
        });
    },
    // 清除关键字
    handleClear() {
      this.keywords = '';
      this.page = 1;
      this.status = 'more';
      this.scrollInfo = []; // 清空楼层数量
      if (this.$refs.childMethod) {
        // this.$refs.childMethod.resetPop();
        this.advancedSearch = {
          typeId: 0,
		  goods_type: 0
        };
      }
      this.handleSearch();
      uni.hideKeyboard();
    },
    // 返回
    back() {
      uni.navigateBack();
    },
    /**
     * @description 增加一条搜索历史记录
     * @param {Object} value 关键词
     */
   async addHistory(value) {
      if (global.token) {
        if (value.trim() == '') return;
		
		if (!value) return;
		var _history = await uni.getStorageSync('SEARCHHISTORY') || [];
		// 判断是否拿到缓存并且判断是否已经包含此数据，否则会报错
		if(!_history.includes(value) && Array.isArray(_history)){
		        	_history.unshift(value);
		        	let history = [...new Set(_history)];
		        	uni.setStorageSync('SEARCHHISTORY', history); 
		}
       
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #fff!important;
}

.page-load{
	pointer-events: none;
}

.head-top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

.nav-bar-wrap {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

.sort-wrap {
  position: fixed;
  left: 0;
  right: 0;
}

.height-100 {
  height: 100rpx;
}

.block-180 {
  width: 180rpx;
  min-width: 180rpx;
  height: 180rpx;
  min-height: 180rpx;
  position: relative;

  image {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
  }

  .null {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    border-radius: 8rpx;
    background-color: rgba(0, 0, 0, 0.45);
    color: #ffffff;
    font-size: 36rpx;
    text-align: center;
    line-height: 180rpx;
  }
}
.list {
	padding: 0 32rpx;
}

.list-item + .list-item {
  border-top: 1rpx solid #eeeeee;
}

.overlay-animate {
  position: fixed;
}

.float-action {
  width: 72rpx;
  height: 72rpx;
  border-radius: 50%;
  // background-color: rgba(165, 165, 165, .85);
  position: fixed;
  right: 20rpx;
  bottom: 280rpx;
  z-index: 996;
  border: 1rpx solid #cccccc;

  .cuIcon-cart {
    color: #cccccc;
  }
}

.animate {
  position: fixed;
  border-radius: 50%;
  z-index: 995;
  transform-origin: 50% 50%;
  transition: transform linear 0.5s, left linear 0.5s, top cubic-bezier(0.3, -0.2, 1, 0) 0.5s !important;

  image {
    width: 100rpx;
    height: 100rpx;
    border-radius: 50%;
  }
}

// 商品卡片line
.fu-goods-line {
  /* min-height: 570rpx; */
  // padding: 24rpx;
  overflow: hidden;
  background-color: #ffffff;
  padding: 24rpx 0 24rpx 24rpx;
  display: flex;
  // margin: 0 24rpx;
  margin-top: 24rpx;
  border-radius: 24rpx;

  .block-246 {
    width: 220rpx;
    height: 220rpx;
    border-radius: 16rpx;
    overflow: hidden;
    background-color: #eeeeee;

    image {
      width: 100%;
      height: 100%;
      border-radius: 6rpx;
    }
  }

  .content {
    padding: 0 24rpx;
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
}

// 商品卡片block
.fu-goods-block {
  overflow: hidden;
  margin-bottom: 20rpx;
  padding: 0 10rpx;

  .wrap-box {
    background-color: #ffffff;
    border-radius: 24rpx;

    .square-wrap {
      width: 100%;
      height: 0;
      padding-bottom: 100%;
      box-sizing: border-box;
      position: relative;

      .square-box {
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        border-radius: 24rpx 24rpx 0 0;
        overflow: hidden;
        .image {
          width: 100%;
          height: 100%;
          border-radius: 24rpx 24rpx 0 0;
        }
      }
    }

    .image {
      width: 100%;
      border-radius: 24rpx 24rpx 0 0;
    }
  }

  .content {
    padding: 20rpx;
    height: 274rpx;
  }
}

.merchant-coupon-item {
  border: 1rpx solid #ff6464;
  opacity: 1;
  border-radius: 6rpx;
  color: #ff6464;
  padding: 0 10rpx;
  margin: 5rpx;
}

.merchant-info {
  // margin-right: 140rpx;
  image{
    width: 24rpx;
    height: 22.5rpx;
    margin-right: 8rpx;
  }
  font-size: 24rpx;
  .text {
    margin-left: 24rpx;

    .icon {
      font-size: 24rpx;
      margin-left: 3rpx;
    }
  }
}

// 店铺信息 start
.fu-shop-item {
  width: 100%;
  display: flex;
  // align-items: center;
  padding: 32rpx 0;
  justify-content: space-between;

  .fu-shop-logo {
    width: 124rpx;
    height: 124rpx;
    border-radius: 8rpx;
    overflow: hidden;
    margin-right: 16rpx;
	flex-shrink: 0;

    .fu-shop-logo-pic {
      width: 100%;
      height: 100%;
    }
  }

  .fu-shop-main {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
		padding-bottom: 10rpx;
		flex: 1;
		overflow: hidden;


    .fu-shop-name {
      display: flex;
	  .store_name {
		  flex: 1;
		  display: -webkit-box;
		  -webkit-box-orient: vertical;
		  overflow: hidden;
		  word-break: break-all;
		  -webkit-line-clamp: 2;
	  }
	  .fu-shop-go {
		  width: 140rpx;
		  height: 56rpx;
		  border-radius: 28rpx;
		  text-align: center;
		  line-height: 56rpx;
		  background-color: #FF6F27;
		  font-size: 24rpx;
		  color: #fff;
	  }
    }
	.time {
		font-size: 22rpx;
		color: #999;
		margin-top: 4rpx;
		.icon {
			width: 24rpx;
			height: 24rpx;
			margin-right: 16rpx;
		}
		view {
			&:first-of-type {
				margin-right: 40rpx;
			}
		}
	}
	.address {
		margin-top: 10rpx;
		overflow: hidden;
		font-size: 22rpx;
		.icon {
			width: 24rpx;
			height: 24rpx;
			margin-right: 16rpx;
			flex-shrink: 0;
		}
		.addr {
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}
	}
  }
}

// 店铺信息 end
.item-activity-label {
  padding: 2rpx 5rpx;
  /* margin: 5rpx; */
  font-size: 24rpx;
  border-radius: 6rpx;
  border: 1px solid;
  margin: 0rpx 1px 0px;
  display: inline-block;
  transform: scale(0.8);
}

.item-goods-label {
  background-image: linear-gradient(to right, #ff9700, #ed1c24);
  padding: 2rpx 5rpx;
  color: #ffffff;
  font-size: 24rpx;
  border-radius: 6rpx;
  margin-right: 9rpx;
}
.comeIn {
  flex-shrink: 0;
}

.search-form {
  .search-icon{
    width: 24rpx;
    height: 24rpx;
    margin-left: 24rpx;
    margin-right: 12rpx;
  }
}
.item-goods-label {
  padding: 2rpx 8rpx;
  color: #ff6464;
  font-size: 24rpx;
  margin-right: 6rpx;
  background: rgba(255, 100, 100, 0.1);
  /* opacity: 0.1; */
  border-radius: 4rpx;
}
.item-activity-label {
  padding: 0 8rpx;
  height: 32rpx;
  line-height: 30rpx;
  border: 1px solid #fa2033;
  opacity: 1;
  border-radius: 4rpx;
  font-size: 20rpx;
  font-family: PingFang SC;
  font-weight: 400;
  color: #fa2033;
  margin-right: 16rpx;
  &:nth-of-type(1) {
    border: 1px solid #0a7ce6;
    color: #0a7ce6;
  }
}
.padding-lr-24 {
  padding: 0 24rpx;
}
.padding-lr-4 {
  padding: 0 4rpx;
}
.sales-number {
  margin-top: 16rpx;
}
.through-price {
  margin-left: 16rpx;
  color: #bfbfbf;
}
.share-box {
    position: absolute;
    height: 64rpx;
    width: 204rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: $bgtheme;
    color: #FFFFFF;
    border-radius: 4rpx;
    font-size: 22rpx;
    bottom: 24rpx;
    right: 24rpx;
    image {
      width: 24rpx;
      height: 24.5rpx;
      margin-right: 10rpx;
    }
  }
  .fan-price{
    color: #FF9B26;
    font-size: 22rpx;
  }
</style>
